#pragma once

#include <iostream>
#include <cstdio>
#include <cerrno>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

using namespace std;

const string comm_path = "./myfifo";

#define DefaultFd -1
#define Creater 1
#define User 2
#define Read O_RDONLY
#define Write O_WRONLY
#define BaseSize 4096

class NamePipe
{
private:
    bool OpenNamePipe(int mode)
    {
        _id = open(_fifo_path.c_str(), mode);
        if (_id < 0)
            return false;
        return true;
    }

public:
    NamePipe(const string& path, int who)
        :_fifo_path(path)
        , _id(who)
        , _fd(DefaultFd)
    {
        if (_id == Creater)
        {
            int res = mkfifo(_fifo_path.c_str(), 0666);
            if (res != 0)
            {
                perror("mkfifo");
            }
            cout << "creater creat named pipe" << endl;
        }
    }

    bool OpenForRead()
    {
        return OpenNamePipe(Read);
    }

    bool OpenForWrite()
    {
        return OpenNamePipe(Write);
    }

    // const &: const std::string &XXX
    // *      : std::string *
    // &      : std::string & 
    int ReadNamePipe(string* out)
    {
        char buffer[BaseSize];
        int n = read(_fd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            *out = buffer;
        }
        return n;
    }

    int WriteNamePipe(string& in)
    {
        return write(_fd, in.c_str(), in.size());
    }

    ~NamePipe()
    {
        if (_id == Creater)
        {
            int res = unlink(_fifo_path.c_str());
            if (res != 0)
            {
                perror("unlink");
            }
            cout << "creater free name pipe" << endl;
        }
        if (_fd != DefaultFd)
            close(_fd);
    }

private:
    string _fifo_path;
    int _id;
    int _fd;
};